package cn.calm.swing.osgi.host.tracker;

import java.awt.Container;
import java.util.HashMap;
import java.util.Map;

import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;

import cn.calm.swing.osgi.api.ProjectService;
import cn.calm.swing.osgi.host.ui.MainFrame;
import cn.calm.swing.osgi.host.ui.ProjectPanel;

public class ProjectServiceTracker extends
		ServiceTracker<ProjectService, ProjectService> {
	protected final static int ADDED = 1, REMOVED = 2, MODIFIED = 3;
	private Map<Long,ProjectPanel> projectMap=new HashMap<Long, ProjectPanel>();
	private MainFrame frame;
	
	public ProjectServiceTracker(BundleContext context, MainFrame frame) {
		super(context, ProjectService.class, null);
		this.frame=frame;
	}

	@Override
	public ProjectService addingService(ServiceReference<ProjectService> reference) {
		ProjectService service = super.addingService(reference);
		processProjectPanel(ADDED,reference,service);
		return service;
	}

	@Override
	public void modifiedService(ServiceReference<ProjectService> reference,
			ProjectService service) {
		processProjectPanel(MODIFIED,reference,service);
		super.modifiedService(reference, service);
	}

	@Override
	public void removedService(ServiceReference<ProjectService> reference,
			ProjectService service) {
		processProjectPanel(REMOVED,reference,service);
		super.removedService(reference, service);
	}
	
	private void processProjectPanel(int action,ServiceReference<ProjectService> reference,
			ProjectService service){
		Container contentPane = frame.getContentPane();
		ProjectPanel projectPanel;
		switch(action){
		case MODIFIED:
			projectPanel = projectMap.get(service.getProject().getId());
			contentPane.remove(projectPanel);
			projectMap.remove(service.getProject().getId());
		case ADDED:{
			projectPanel=new ProjectPanel(service,context);
			contentPane.add(projectPanel);
			projectMap.put(service.getProject().getId(), projectPanel);
			break;
		}
		case REMOVED:{
			projectPanel = projectMap.get(service.getProject().getId());
			contentPane.remove(projectPanel);
			projectMap.remove(service.getProject().getId());
		}
		}
		frame.validate();
		frame.repaint();
	}
}
